﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace Aspfm.Main
{
    public class SessionTool
    {
        public const char splitChar = '★';
        public static string CookieName
        {
            get
            {
                string Authority = "";
                string ApplicationPath = "Aspfm";
                if (System.Web.HttpContext.Current != null)
                {
                    Authority = System.Web.HttpContext.Current.Request.Url.Authority;
                    ApplicationPath = System.Web.HttpContext.Current.Request.ApplicationPath;
                }
                return Regex.Replace(Authority + ApplicationPath, "[^A-Za-z0-9]", "");
            }
        }

        public static void SetUserCurrent(IPrincipal principal)
        {
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                //HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity("AspfmUser"), null);
                HttpContext.Current.User = principal;
            }
        }
        public static void SetUserCurrent(UserIdentity user)
        {
            IPrincipal principal = new UserPrincipal<int>(user);
            SetUserCurrent(principal);
        }
        public static void SetUserCookie(UserIdentity user)
        {
            if (string.IsNullOrEmpty(user.LoginGuid))
            {
                user.SetLoginGuid();
            }
            SetUserCurrent(user);
            ////创建票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user.GetUserString(),false, 30);
            ////加密票据
            string authTicket = FormsAuthentication.Encrypt(ticket);
            ////存储为cookie
            HttpCookie cookie = new HttpCookie(CookieName, authTicket);
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.HttpOnly = true;
            //cookie.Expires = rememberMe ? expirationDate : DateTime.MinValue;
            if (HttpContext.Current != null)
            {
                //cookie.Domain = System.Web.HttpContext.Current.Request.Url.Authority;
                HttpContext.Current.Response.Cookies.Set(cookie);
            }
            ////或者
            //FormsAuthentication.SetAuthCookie(authTicket, false, "/");
        }
        public static void Clear()
        {
            Thread.CurrentPrincipal = null;
            if (HttpContext.Current != null)
            {  //清除身份验证Cookie
                FormsAuthentication.SignOut();
                HttpContext.Current.Response.Cookies.Clear();
                HttpContext.Current.Response.Cookies[CookieName].Expires = DateTime.Now.AddDays(-10);
            }
        }

        public static bool Longin(string cookieValue)
        {
            if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                return true;
            }
            if (string.IsNullOrEmpty(cookieValue))
            {
                return false;
            }

            FormsAuthenticationTicket ticket = null;
            try
            {
                ticket = FormsAuthentication.Decrypt(cookieValue);
                //if (ticket.Expired)
                //{
                //    return new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(FormAuthenticationFilterAttribute.SessionMessage, Encoding.UTF8) };
                //}
            }
            catch { }
            if (ticket == null)
            {
                return false;
            }
            //这里可以对FormsAuthenticationTicket对象进行进一步验证
            var principal = new GenericPrincipal(new FormsIdentity(ticket), null);
            SessionTool.SetUserCurrent(principal);
            return true;
        }
    }
}
